package org.jeecg.glr.controller;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SysUtil;
import org.jeecg.glr.entity.GlrColumn;
import org.jeecg.glr.entity.GlrSensor;
import org.jeecg.glr.entity.GlrSensorData;
import org.jeecg.glr.entity.GlrSensorSet;
import org.jeecg.glr.iframe.util.AjaxJson;
import org.jeecg.glr.service.IGlrColumnService;
import org.jeecg.glr.service.IGlrSensorService;
import org.jeecg.glr.service.IGlrSensorSetService;
import org.jeecg.glr.service.IGlrVideoYsService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.PositionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/glr/glrHomeController")
@Slf4j
public class GlrHomeController extends JeecgController<GlrColumn, IGlrColumnService> {

    @Autowired
    private IGlrVideoYsService glrVideoYsService;

    @Autowired
    private IGlrSensorService glrSensorService;
    @Resource
    private IGlrSensorSetService glrSensorSetService;

    /**
     * 取所有传感器
     *
     * @param model
     * @return
     */
    @GetMapping(value = "/getMainData")
    public Result<?> getMainData(Model model, HttpServletRequest request) throws Exception {
        AjaxJson j = new AjaxJson();


        String codeSql = "";
        String userType=SysUtil.getUserInfo().getUserType();
        if(!userType.equals(SysConstant.SYS_USER_TYPE_ADMIN)&&!userType.equals(SysConstant.SYS_USER_TYPE_0)){
            codeSql="  AND sys_company_code='"+SysUtil.getUserInfo().getSysCompanyCode()+"'";
        }
        String sql1 = "select 'gateway'as a0,count(*) as a1,sum(if(current_work_status='Y',1,0)) as a2 from glr_gateway where 1=1 " + codeSql;
        String sql2 = "select 'light'as a0,count(*) as a1,0 as a2 from glr_light where 1=1 " + codeSql;
        String sql3 = "select 'led'as a0,count(*) as a1,sum(if(status='Y',1,0)) as a2 from glr_led where 1=1 " + codeSql;
        String sql4 = "select 'sensor'as a0,count(*) as a1,sum(if(status='Y',1,0)) as a2 from glr_sensor where 1=1 " + codeSql;
        String sql5 = "select 'video'as a0,count(*) as a1,sum(if(equipment_status='Y',1,0)) as a2 from glr_video where 1=1 " + codeSql;
        String sql6 = "select 'radio'as a0,count(*) as a1,sum(if(status<>'Offline',1,0)) as a2 from glr_radio where 1=1 " + codeSql;
        String sql7 = "select 'fault_alerm'as a0,count(*) as a1,0 as a2 from glr_fault_alerm where 1=1 and status<>'" + GLRConstant.YN_Y + "' " + codeSql;
        int year = DateUtils.getYear();
        String sql8 = "select 'light_data' as a0,sum(day_Electricity) as a1,avg(avg_power) as a2 from glr_light_data where date_format(create_time, '%Y')='" + year + "'" + codeSql;
        String stsql = sql1 + "\n union \n" + sql2 + "\n union \n" + sql3 + "\n union \n" + sql4 + "\n union \n" + sql5 + "\n union \n" + sql6 + "\n union \n" + sql7 + "\n union \n" + sql8;
        List<Map<String, Object>> dataList = glrVideoYsService.doGetListForJdbc(stsql);
        //总数
        int ledcount = 0;
        int gatewaycount = 0;
        int sensorcount = 0;
        int videocount = 0;
        int radiocount = 0;
        //在线
        int zaixian_led = 0;
        int zaixian_gateway = 0;
        int zaixian_sensor = 0;
        int zaixian_video = 0;
        int zaixian_radio = 0;

        int guzhang_count = 0;

        int power_sum = 0;
        int power_avg = 0;

        int all_count = 0;
        int ligth_count = 0;
        for (Map<String, Object> a1 : dataList) {
            String sta0 = "0";
            if (a1.get("a0") != null) {
                sta0 = a1.get("a0").toString();
            }
            String sta1 = "0";
            if (a1.get("a1") != null) {
                sta1 = a1.get("a1").toString();
            }
            String sta2 = "0";
            if (a1.get("a2") != null) {
                sta2 = a1.get("a2").toString();
            }
            int count = (int) Double.parseDouble(sta1);
            int icounta2 = (int) Double.parseDouble(sta2);
            if ("sensor".equals(sta0)) {
                sensorcount = count;
                zaixian_sensor = icounta2;
                all_count = all_count + count;
            }
            if ("led".equals(sta0)) {
                ledcount = count;
                zaixian_led = icounta2;
                all_count = all_count + count;
            }
            if ("video".equals(sta0)) {
                videocount = count;
                zaixian_video = icounta2;
                all_count = all_count + count;
            }
            if ("radio".equals(sta0)) {
                radiocount = count;
                zaixian_radio = icounta2;
                all_count = all_count + count;
            }

            if ("gateway".equals(sta0)) {
                gatewaycount = count;
                zaixian_gateway = icounta2;
                all_count = all_count + count;
            }
            if ("light".equals(sta0)) {
                ligth_count = count;
                all_count = all_count + count;
            }

            if ("fault_alerm".equals(sta0)) {
                guzhang_count = count;
            }
            if ("light_data".equals(sta0)) {
                power_sum = count;
                power_avg = icounta2;
            }
        }
        int zaixianlv = (int) (Double.valueOf(zaixian_gateway + zaixian_radio + zaixian_video + zaixian_led + zaixian_sensor) / Double.valueOf(all_count) * 100);


        GlrSensorData glrSensorData= glrSensorService.getGlrSensorOne(null,request);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("all_count", all_count);  //所有的设备数
        map.put("gatewaycount", gatewaycount);
        map.put("zaixian_gateway", zaixian_gateway);
        map.put("zaixian_radio", zaixian_radio);
        map.put("radiocount", radiocount);
        map.put("zaixian_video", zaixian_video);
        map.put("videocount", videocount);
        map.put("zaixian_led", zaixian_led);
        map.put("ledcount", ledcount);
        map.put("sensorcount", sensorcount);
        map.put("zaixian_sensor", zaixian_sensor);
        map.put("zaixianlv", zaixianlv);
        map.put("guzhang_count", guzhang_count);

        map.put("glrSensorData", glrSensorData);

        map.put("power_sum", power_sum);  //当年总用量
        map.put("power_avg", power_avg);  //当年平均功率
        map.put("ligth_count", ligth_count);
        map= getEchartLightPoweerDate(map);
        return Result.ok(map);
    }

    /**
     * @return
     * @throws Exception
     */
    public Map<String, Object> getEchartLightPoweerDate(Map<String, Object> map) throws Exception {
        LoginUser loginUser = SysUtil.getUserInfo();
        AjaxJson j = new AjaxJson();
        List<String> dateList = new ArrayList<>();
        List<Double> electricityList = new ArrayList<>();
        List<Double> avg_powerList = new ArrayList<>();
        List<String> day_economy_electricityList = new ArrayList<>();
        String codeSql = "";
        String userType=SysUtil.getUserInfo().getUserType();
        if(!userType.equals(SysConstant.SYS_USER_TYPE_ADMIN)&&!userType.equals(SysConstant.SYS_USER_TYPE_0)){
            codeSql="  AND A.sys_company_code='"+SysUtil.getUserInfo().getSysCompanyCode()+"'";
        }
        try {
            String stSql = "select \n" +
                    "sum(a.day_electricity) as day_electricity,\n" +
                    "sum(a.day_economy_electricity) as day_economy_electricity,\n" +
                    "AVG(a.avg_power) as avg_power,\n" +
                    "date_format(create_time, '%y%m%d') as create_date\n" +
                    "FROM glr_light_data a\n" +
                    "where 1=1 "+codeSql;
            //月
            String yesterday1 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getEndDayOfMonth());
            String yesterday2 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getBeginDayOfMonth());
            String DataSql = stSql + " and date(create_time) between '" + yesterday2 + "' and '" + yesterday1 + "' group by date(create_time)";
            List<Map<String, Object>> ss = glrVideoYsService.doGetListForJdbc(DataSql);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date d2 = simpleDateFormat.parse(yesterday2);
            Date d1 = simpleDateFormat.parse(yesterday1);
            Calendar dd1 = Calendar.getInstance();//定义日期实例
            dd1.setTime(d1);//设置日期起始时间
            dd1.add(Calendar.HOUR, 1);

            Calendar dd2 = Calendar.getInstance();//定义日期实例
            dd2.setTime(d2);//设置日期起始时间


            while (dd2.getTime().before(dd1.getTime())) {//判断是否到结束日期
                String str = new SimpleDateFormat("yyyyMMdd").format(dd2.getTime());
                str = str.substring(2);
                boolean bfind = false;
                for (Map<String, Object> ss_1 : ss) {
                    String create_date = ss_1.get("create_date").toString();
                    String day_electricity = ss_1.get("day_electricity").toString();
                    String avg_power = ss_1.get("avg_power").toString();
                    String day_economy_electricity = ss_1.get("day_economy_electricity").toString();
                    if (create_date.equals(str)) {
                        bfind = true;
                        dateList.add(create_date);
                        electricityList.add(Math.ceil(Double.parseDouble(day_electricity)));
                        avg_powerList.add(Math.ceil(Double.parseDouble(avg_power)));
                        day_economy_electricityList.add(day_economy_electricity);
                        break;
                    }
                }
                if (bfind) {

                } else {
                    electricityList.add(0d);
                    avg_powerList.add(0d);
                    day_economy_electricityList.add("0");
                    dateList.add(str);
                }
                dd2.add(Calendar.DATE, 1);//进行当前日期月份加1
            }

            double dayelectricity = 0;
            double day_economy_electricity = 0;
            for (int i = 0; i < electricityList.size(); i++) {
                dayelectricity = dayelectricity + electricityList.get(i);
                day_economy_electricity = day_economy_electricity + Double.parseDouble(day_economy_electricityList.get(i));
            }
            int jieyuemenghao = (int) (day_economy_electricity / (day_economy_electricity + dayelectricity) * 100);

            map.put("dateList", dateList);
            map.put("electricityList", electricityList);
            map.put("day_economy_electricity", Math.round(day_economy_electricity));
            map.put("avg_powerList", avg_powerList);
            map.put("jieyuemenghao", jieyuemenghao);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return map;

    }




    /**
     * 大屏取数据
     *
     */
    @GetMapping(value = "/getGlrMainSenSor")
    public Result<?> getGlrMainSenSor(Model model, HttpServletRequest request) throws Exception{
        GlrSensorData sensor = glrSensorService.getGlrSensorOne(null,request);
        sensor.setWindDirection(PositionUtil.getWindDirection(sensor.getWindDirection()));
        return Result.ok(sensor);
    }
    @GetMapping(value = "/getGlrMainChart")
    public Result<?> getGlrMainChart(Model model, HttpServletRequest request) throws Exception{
       Map<String,Object> map = new HashMap<>();
       List<Double> humidityList = new ArrayList<>();
       List<Double> temperatureList = new ArrayList<>();
       List<Double> pm25List = new ArrayList<Double>();
       List<Double> pm10List = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        String sql="select IFNULL(temperature_avg,0) as temperature_avg,IFNULL(pm25_avg,0) as pm25_avg,IFNULL(pm10_avg,0) as pm10_avg,IFNULL(humidity_avg,0) as humidity_avg, round(avg(s.humidity),1) as humidity,round(avg(s.temperature),1) as temperature,round(avg(s.pm25),1) as pm25,round(avg(s.pm10),1) as pm10,date_format(s.create_time, '%y%m%d') as create_date from glr_sensor_data s  where 1=1";
        String yesterday1 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getEndDayOfMonth());
        String yesterday2 = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.getBeginDayOfMonth());
        String DataSql = sql + " and date(create_time) between '" + yesterday2 + "' and '" + yesterday1 + "' group by date(create_time)";
        List<Map<String, Object>> ss = glrVideoYsService.doGetListForJdbc(DataSql);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date d2 = simpleDateFormat.parse(yesterday2);
        Date d1 = simpleDateFormat.parse(yesterday1);
        Calendar dd1 = Calendar.getInstance();//定义日期实例
        dd1.setTime(d1);//设置日期起始时间
        dd1.add(Calendar.HOUR, 1);
        Calendar dd2 = Calendar.getInstance();//定义日期实例
        dd2.setTime(d2);//设置日期起始时间
        SimpleDateFormat sft = new SimpleDateFormat("yyyyMMdd");
        String newDate=sft.format(new Date());
        newDate = newDate.substring(2);
        GlrSensorData sensor = new GlrSensorData();
        while (dd2.getTime().before(dd1.getTime())) {//判断是否到结束日期
            String str = sft.format(dd2.getTime());
            str = str.substring(2);
            boolean bfind = false;
            for (Map<String, Object> ss_1 : ss) {
                String create_date = ss_1.get("create_date").toString();
                if(str.equals(newDate)){
                    sensor.setTemperature(Double.parseDouble(ss_1.get("temperature").toString()));
                    sensor.setHumidity(Double.parseDouble(ss_1.get("humidity").toString()));
                    sensor.setPm10(Double.parseDouble(ss_1.get("pm10").toString()));
                    sensor.setPm25(Double.parseDouble(ss_1.get("pm25").toString()));
                }
                if (create_date.equals(str)) {
                    bfind = true;
                    dateList.add(create_date);
                    if(create_date.equals(newDate)){
                        humidityList.add(Double.parseDouble(ss_1.get("humidity").toString()));
                        temperatureList.add(Double.parseDouble(ss_1.get("temperature").toString()));
                        pm10List.add(Double.parseDouble(ss_1.get("pm10").toString()));
                        pm25List.add(Double.parseDouble(ss_1.get("pm25").toString()));
                    }else{
                        humidityList.add(Double.parseDouble(ss_1.get("humidity_avg").toString()));
                        temperatureList.add(Double.parseDouble(ss_1.get("temperature_avg").toString()));
                        pm10List.add(Double.parseDouble(ss_1.get("pm10_avg").toString()));
                        pm25List.add(Double.parseDouble(ss_1.get("pm25_avg").toString()));
                    }
                    break;
                }
            }
            if (!bfind) {
                humidityList.add(0d);
                temperatureList.add(0d);
                pm10List.add(0d);
                dateList.add(str);
                pm25List.add(0d);
                if(str.equals(newDate)){
                    sensor.setTemperature(0d);
                    sensor.setHumidity(0d);
                    sensor.setPm10(0d);
                    sensor.setPm25(0d);
                }
            }

            dd2.add(Calendar.DATE, 1);//进行当前日期月份加1
        }
        map.put("dateList", dateList);

        map.put("humidityList", humidityList);
        map.put("temperatureList", temperatureList);
        map.put("pm25List", pm25List);
        map.put("pm10List", pm10List);
        List<GlrSensor> sensorList=glrSensorService.getSenSorAll();
        GlrSensorSet sensorSet= glrSensorSetService.getSenSorSetByStatus();
        if(sensorSet!=null){
            if(sensor.getTemperature()>sensorSet.getAlarmTemperature()){
                sensor.setAlarmFlagWd(true);
            }
            if(sensor.getHumidity()>sensorSet.getAlarmHumidity()||sensor.getHumidity()<sensorSet.getAlarmMinHumidity()){
                sensor.setAlarmFlagSd(true);
            }
            if(sensor.getPm25()>sensorSet.getAlarmPm25()){
                sensor.setAlarmFlagPm25(true);
            }
            if(sensor.getPm10()>sensorSet.getAlarmCo2()){
                sensor.setAlarmFlagCo2(true);
            }
        }
        map.put("sensor", sensor);


        map.put("sensorList",sensorList);
        map.put("sensorSet",sensorSet);
        return Result.ok(map);
    }

    @GetMapping(value = "/getGlrMainData")
    public Result<?> getGlrMainData(Model model, HttpServletRequest request) throws Exception{
        Map<String,Object> map = new HashMap<>();
        List<GlrSensor> sensorList=glrSensorService.getSenSorAll();
        map.put("sensorList",sensorList);
        return Result.ok(map);
    }
}
